package cc.iits.demo.crane.service.core.biz;

import cc.iits.demo.crane.api.bo.Result;
import cc.iits.demo.crane.api.bo.biz.HistoryBO;
import cc.iits.demo.crane.api.service.biz.HistoryService;
import cc.iits.demo.crane.dao.dataobject.HistoryDO;
import cc.iits.demo.crane.dao.mapper.HistoryMapper;
import cc.iits.demo.crane.service.core.CraneServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class HistoryServiceImpl  extends CraneServiceImpl<HistoryMapper, HistoryDO> implements HistoryService {

    /**
     * 添加
     *
     * @param history
     * @return
     */
    @Override
    public boolean insert(HistoryBO history) {
        verify(history);

        HistoryDO entity=change(history, HistoryDO.class);
        entity.setCreateTime(new Date());
        return baseMapper.insert(entity) > 0;
    }

    /**
     * 查询
     *
     * @param params
     * @return
     */
    @Override
    public Result<HistoryBO> select(HistoryBO params) {
        if (params == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (StringUtils.isEmpty(params.getSid())) {
            throw new RuntimeException("会话编号不能为空");
        }

        LambdaQueryWrapper<HistoryDO> wrapper = new LambdaQueryWrapper<HistoryDO>().eq(HistoryDO::getSid, params.getSid());
        wrapper.orderByDesc(HistoryDO::getBeginTime);
        Page pages = PageHelper.startPage(params.getPage(), params.getRows());
        List<HistoryBO> list = change(list(wrapper), HistoryBO.class);
        return new Result<>(list, pages.getTotal());
    }

    /**
     * 参数验证
     *
     * @param history
     */
    private void verify(HistoryBO history) {
        if (history == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (StringUtils.isEmpty(history.getSid())) {
            throw new RuntimeException("会话编号不能为空");
        }
        if (history.getMachine() == null) {
            throw new RuntimeException("天车不能为空");
        }
        if (history.getDirection() == null) {
            throw new RuntimeException("方向不能为空");
        }
        if (!(history.getDirection() == 1 || history.getDirection() == 2 || history.getDirection() == 3 || history.getDirection() == 4)) {
            throw new RuntimeException("方向错误");
        }
        if (history.getBeginTime() == null) {
            throw new RuntimeException("开始时间不能为空");
        }
        if (history.getEndTime() == null) {
            throw new RuntimeException("结束时间不能为空");
        }
        if (history.getTotal() == null) {
            throw new RuntimeException("耗时不能为空");
        }
    }
}
